<template>
  <view class="page goods">
    <swiper class="g-banner" indicator-dots indicator-active-color="#db187c" autoplay>
      <swiper-item class="b-item" v-for="(item, i) in gallery" :key="i">
        <view class="b-item__inner">
          <a-img @tap="previewImage(item)" :src="item"></a-img>
        </view>
      </swiper-item>
    </swiper>
    <view class="g-block g-base-info">
      <van-skeleton title :loading="false" row="2">
        <price-wrap sub="起" :value="amountRetail(goods)"></price-wrap>
        <text class="g-name">{{ $_.get(goods, "name") }}</text>
        <text class="g-tag">{{ $_.get(goods, "description") }}</text>
      </van-skeleton>
    </view>
    <view class="g-block g-all-specs" @tap="getShopCartList('checkSpec')">
      <view class="s-left">规格</view>
      <view class="s-tag">颜色({{ getSpecColor.length }}种)</view>
      <view class="s-tag">尺码({{ getSpecSize.length }}种)</view>
      <view class="s-right">
        <view class="r-text">查看更多</view>
        <text class="s-icon iconfont">&#xe641;</text>
      </view>
    </view>
    <view class="g-block">
      <text class="g-block__label">商品参数</text>
      <uParse :content="goods.detailMobileText" :noData="noData"></uParse>
    </view>
    <view class="g-block">
      <text class="g-block__label">更多精选商品</text>
      <view class="goods-wrap">
        <a-goods-card v-for="(g, i) in recommendGoodsList" :key="i" :goods="g"></a-goods-card>
      </view>
      <view class></view>
    </view>
    <a-logo type="text"></a-logo>
    <view class="g-btm box-gap" :class="{ active: isCompatibility }">
      <view type="default" @tap="fav" class="btn">
        <image class="b-img" :src="'icon/notlike.png' | prefixOssUrl" />
        <view class="b-text">喜欢</view>
      </view>
      <button type="default" open-type="share" class="btn">
        <view class="iconfont icon share">&#xe6b5;</view>
        <view class="b-text">分享</view>
      </button>

      <uni-badge :text="shoppingCartQuantity" absolute
        :custom-style="{ backgroundColor: '#db187c', borderRadius: '10rpx' }">
        <view @tap="swi('/pages/cart/index')" class="btn">
          <view class="iconfont icon cart">&#xe60c;</view>
          <view class="b-text">购物车</view>
        </view>
      </uni-badge>

      <view class="g-btm_add-cart" :class="{ 'g-btm_add-cart--disable': goods.type === 2 }"
        @tap="getShopCartList('addCart')">加入购物车
      </view>
    </view>
    <van-popup class="g-popup" :show="popup.attr.isShow" round position="bottom" custom-style="height: 80%" closeable
      @close="popup.attr.isShow = false">
      <view class="p-main">
        <view class="m-header">
          <view class="t-left">
            <a-img-loader :src="goods.thumbnail" />
          </view>
          <view class="t-right">
            <view class="r-name">{{ $_.get(goods, "name") }}</view>
            <price-wrap sub="起" :value="amountRetail(goods)"></price-wrap>
          </view>
        </view>
        <view class="m-tabs">
          <view class="iconfont arrow-left" @tap="positionTo(-1)">
            {{
              getSpecColor.length > 3 && !popup.attr.isScrolltoupper
                ? "&#xe64f;"
                : ""
            }}
          </view>
          <scroll-view class="t-list" :scroll-into-view="scrollIntoView" scroll-x="true" upper-threshold="10"
            lower-threshold="10" @scrolltoupper="popup.fn.scrolltoupper()" @scrolltolower="popup.fn.scrolltolower()">
            <view class="l-item" :id="`colour${i}`" :class="{ 'l-item-active': popup.attr.tabIndex === i }"
              v-for="(item, i) in getSpecColor" :key="i" @tap="popup.attr.tabIndex = i">
              <uni-badge :text="clothesTotal[item.label]" absolute :custom-style="{
                backgroundColor: '#db187c',
                borderRadius: '10rpx',
              }">{{ item.label }}</uni-badge>
            </view>
          </scroll-view>
          <view class="iconfont arrow-right" @tap="positionTo(1)">
            {{
              getSpecColor.length > 3 && !popup.attr.isScrolltolower
                ? "&#xe641;"
                : ""
            }}
          </view>
        </view>
        <template v-if="shopCartList.label">
          <view class="m-list" v-for="(item, index) in getSpecColor" :key="index"
            v-show="index === popup.attr.tabIndex">
            <view class="m-list-item" v-for="(item, i) in shopCartList.val[getSpecColor[index].label]" :key="i">
              <view class="i-size">{{ item["尺码"] }}</view>
              <view class="i-status" :style="!item.stock && 'color:#999' ">{{item.stock?'有货':'无货'}}</view>
              <counter max="1e+15" 
                :value="get(registerList,`${getSpecColor[index].label}.${item.id}`,0)" 
                @input="totalizeFunc($event, item.id, getSpecColor[index].label)"
              >
              </counter>
            </view>
          </view>
        </template>
        <view class="m-footer" v-if="goods.type === 1">
          <view class="f-left">已选：<text class="l-text">{{ clothesTotal.amount }}</text>件</view>
          <view class="f-right" @tap="cardAdd">加入购物车</view>
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script>
  import { appConfig } from '@/config/app';
  import PriceWrap from "@/components/price-wrap";
  import uParse from "@/components/gaoyia-parse/parse";
  import counter from "@/components/counter";

  import _ from "lodash";

  import {
    model
  } from "@/model";

  const {
    PageBo,
    Goods,
    PurchanseCart
  } = model.collection;

  export default {
    components: {
      PriceWrap,
      uParse,
      counter,
    },
    data() {
      return {
        params: {},
        goods: new Goods(),
        recommendGoodsList: [],
        detailMobileText: "",
        paddingBottom: "0",
        noData: '<div style="color: red;text-align:center;">~暂无相关商品详情~</div>',
        shopCartList: {},
        registerList: {},
        shoppingCartQuantity: 0,
        scrollIntoView: "",
        popup: {
          attr: {
            tabIndex: 0,
            isShow: false,
            isScrolltoupper: true,
            isScrolltolower: false,
          },
          fn: {
            scrolltoupper: () => {
              this.popup.attr.isScrolltoupper = true;
              this.popup.attr.isScrolltolower = false;
            },
            scrolltolower: () => {
              this.popup.attr.isScrolltoupper = false;
              this.popup.attr.isScrolltolower = true;
            },
          },
        },
      };
    },
    onLoad(params) {
      this.init(params);
      uni.showShareMenu({
        withShareTicket: true,
        menus: ["shareAppMessage", "shareTimeline"],
      });
    },
    computed: {
      isCompatibility() {
        return this.getSystemInfo();
      },
      gallery() {
        if (this.goods.gallery) return this.goods.gallery;
        return [];
      },
      getSpecSize() {
        return this._getSpec("尺码");
      },
      getSpecColor() {
        return this._getSpec("颜色");
      },
      clothesTotal() {
        const total = {
          amount: 0,
        };
        for (const [colour, list] of Object.entries(this.registerList)) {
          total.amount += total[colour] = Object.values(list).reduce(
            (a, b) => a + b
          );
        }
        return total;
      },
    },
    methods: {
      init(params) {
        this.params = params;
        PageBo.sendApi("info", {
          params: {
            page: "pageGoods",
          },
          data: {
            query: {
              id: this.params.id,
            },
          },
        }).then((res) => {
          const {
            status,
            data
          } = res;
          if (status) {
            this.goods = new Goods(data.goods);
            this.recommendGoodsList = data.recommendGoodsList;
          }
        });
      },
      previewImage(image) {
        let imgArr = [];
        imgArr.push("https:" + image);
        uni.previewImage({
          urls: imgArr,
          current: imgArr[0],
          longPressActions: {
            itemList: ["发送给朋友", "保存图片", "收藏"],
            success: function (data) {},
            fail: function (err) {
              console.log(err.errMsg);
            },
          },
        });
      },
      fav() {
        this.toast("收藏功能尚在开发中，敬请期待！");
      },
      _getSpec(key) {
        if (
          _.get(this, "goods.goodsSpecCategory.goodsSpecKeyList", []).length === 0
        ) {
          return [];
        }
        const validSpecList = _.get(this, "goods.goodsItemsList", [])
          .map((i) => _.get(i, "specJson", "[]"))
          .map((i) => JSON.parse(i || "[]"))
          .reduce((p, c) => {
            return p.concat(c);
          }, []);
        return _.get(
            _.find(_.get(this, "goods.goodsSpecCategory.goodsSpecKeyList"), (i) => {
              return i.name === key;
            }),
            "goodsSpecValueList"
          )
          .map((i) => ({
            value: i.id,
            label: i.name,
            _raw: i,
          }))
          .filter((i) => {
            return validSpecList.map((i) => i.value_id).includes(i.value);
          });
      },
      positionTo(num) {
        this.scrollIntoView = "";
        let tabIndex = this.popup.attr.tabIndex + num;
        if (tabIndex < 0) {
          tabIndex = 0;
        }
        if (tabIndex > this.getSpecColor.length - 1) {
          tabIndex--;
        }
        Promise.resolve().then(() => {
          this.popup.attr.tabIndex = tabIndex;
          this.scrollIntoView = `colour${tabIndex}`;
        })
      },
      getShopCartList(type = "addCart") {
        if (!this.isLogin) {
          uni.showModal({
            title: '未登录',
            content: '前往登录',
            confirmText: '前往',
            success: (res) => {
              if (res.confirm) {
                this.nav(appConfig.loginUrl)
              }
            }
          });
          return;
        }
        if (this.goods.type === 2 && type === "addCart") {
          this.toast("此商品无法加入购物车");
          return;
        }
        this.popup.attr.isShow = true;
        !this.shopCartList.label &&
          (this.shopCartList = _.get(this, "goods.goodsItemsList", []).reduce(
            (goods, commodity) => {
              let clothes = {
                id: commodity.id,
                stock: Math.max(commodity.stock, 0),
              };
              JSON.parse(_.get(commodity, "specJson", "[]")).forEach((item) => {
                if (goods.label === item.key) {
                  !goods.val[item.value] && (goods.val[item.value] = []);
                  goods.val[item.value].push(clothes);
                  return;
                }
                clothes[item.key] = item.value;
              });
              return goods;
            }, {
              label: "颜色",
              val: {},
            }
          ));
      },
      async cardAdd() {
        this.popup.attr.isShow = false;
        let data = [];
        for (const list of Object.values(this.registerList)) {
          for (const [id, quantity] of Object.entries(list)) {
            data.push({
              goodsItemsId: id,
              quantity,
            });
          }
        }
        let res = await PurchanseCart.sendApi("cardAdd", {
          data,
        });
        if (res.status) {
          this.shoppingCartQuantity += this.clothesTotal.amount;
          this.registerList = {};
        }
      },
      totalizeFunc(e, id, colour) {
        if (!this.registerList[colour]) {
          this.$set(this.registerList, colour, {});
        }
        this.$set(this.registerList[colour], id, e);
      },
    },
  };
</script>

<style lang="less">
  .goods {
    padding-bottom: 261rpx;

    .g-block {
      padding: @box-gap;
      background: #fff;

      &:not(:first-of-type) {
        margin-top: 30rpx;
      }

      &__label {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #343434;
      }

      .goods-wrap {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
        width: 100%;

        a-goods-card {
          flex: 1;
          padding-top: 30rpx;

          &:nth-child(2n) {
            margin-left: 40rpx;
          }

          .img-loader {
            .l-img {
              border: 1rpx solid #f5f6f7;
              border-radius: 20rpx;

              image {
                border-radius: 20rpx;
              }
            }
          }
        }
      }
    }

    .g-banner {
      height: 750rpx;
      background: #7f7f7f;

      .b-item {
        &__inner {
          display: flex;
          height: 750rpx;

          .axq-img {
            width: 100vw;
            height: 750rpx;
          }
        }
      }
    }

    .g-name {
      display: block;
      margin-top: 35rpx;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .g-tag {
      display: block;
      margin-top: 29rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: #999;
    }

    .g-all-specs {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .s-left {
        font-size: 32rpx;
        font-weight: bold;
        color: #343434;
      }

      .s-tag {
        width: 180rpx;
        height: 50rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        text-align: center;
        line-height: 50rpx;
        background: #f5f5f5;
        border-radius: 4rpx;
      }

      .s-right {
        display: flex;
        align-items: center;
        color: #666;

        .r-text {
          height: 50rpx;
          line-height: 50rpx;
          font-size: 26rpx;
          font-weight: 500;
        }

        text {
          font-size: 38rpx;
        }
      }
    }

    .g-btm {
      .flexLayout(@a: center);
      position: fixed;
      bottom: 0;
      z-index: 99;
      width: 100vw;
      height: 100rpx;
      background: #fff;
      box-sizing: border-box;
      box-shadow: 0 5rpx 10rpx 2rpx #1d1414;

      uni-badge {
        /deep/ .uni-badge--x {
          text {
            right: 16rpx !important;
            top: -14rpx !important;
          }
        }
      }

      .b-img {
        display: block;
        width: 36rpx;
        height: 36rpx;
      }

      .btn {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 120rpx;
        height: 80rpx;
        font-size: 30rpx;
        line-height: 40rpx;
        color: #999999;
        background: transparent;
        border: none;

        &::after {
          border-color: transparent;
        }

        .share {
          width: 100%;
          font-size: 49rpx;
          line-height: 39rpx;
          color: #db187c;
        }

        .cart {
          font-size: 49rpx;
          color: #000000;
          line-height: 39rpx;
        }

        .b-text {
          font-size: 24rpx;
          font-weight: 500;
          color: #333;
        }
      }

      &_add-cart {
        width: 360rpx;
        height: 80rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: #fff;
        text-align: center;
        line-height: 80rpx;
        background: #db187c;
        border-radius: 40rpx;

        &--disable {
          opacity: 0.5;
        }
      }
    }

    .active {
      height: 150rpx;
      padding-bottom: 60rpx;
    }

    .van-skeleton {
      padding: 0;
      background: #fff;
    }

    .g-popup {
      .p-main {
        display: flex;
        flex-direction: column;
        z-index: 999;
        width: 100vw;
        height: 100%;

        .m-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 180rpx;
          padding: 20rpx 0;

          .t-left {
            width: 180rpx;
            height: 180rpx;
            margin: 0 30rpx;

            image {
              border-radius: 15rpx;
            }
          }

          .t-right {
            flex: 1;

            .r-name {
              width: 400rpx;
              margin-bottom: 30rpx;
              font-size: 32rpx;
              font-weight: bold;
              color: #333;
            }
          }
        }

        .m-tabs {
          display: flex;
          align-items: center;
          width: 100%;
          height: 90rpx;
          padding: 10rpx 0;
          border-top: 1rpx solid #e5e5e5;
          border-bottom: 1rpx solid #e5e5e5;

          .arrow-left,
          .arrow-right {
            width: 90rpx;
            height: 90rpx;
            text-align: center;
            line-height: 90rpx;
          }

          .t-list {
            width: 570rpx;
            height: 90rpx;
            line-height: 90rpx;
            white-space: nowrap;

            .l-item {
              position: relative;
              display: inline-block;
              width: 190rpx;
              height: 60rpx;
              color: #999;
              text-align: center;
              line-height: 60rpx;

              &-active {
                color: #db187c;

                &::after {
                  position: absolute;
                  left: 56rpx;
                  bottom: -18rpx;
                  content: "";
                  width: 80rpx;
                  height: 7rpx;
                  background: #db187c;
                }
              }
            }
          }
        }

        .m-list {
          flex: 1;
          width: 100%;
          overflow-y: auto;

          &-item {
            display: flex;
            align-items: center;
            padding: 20rpx 0;
            margin: 0 30rpx;
            border-bottom: 1rpx solid #e5e5e5;

            .i-size {
              width: 300rpx;
            }

            .i-status {
              width: 200rpx;
            }
          }
        }

        .m-footer {
          display: flex;
          justify-content: space-around;
          align-items: center;
          width: 100%;
          height: 108rpx;
          box-shadow: 0rpx -2rpx 3rpx 0rpx rgba(24, 24, 24, 0.05);

          .f-left {
            font-size: 30rpx;
            font-weight: bold;
            color: #333;

            .l-text {
              color: #ff0505;
            }
          }

          .f-right {
            width: 360rpx;
            height: 80rpx;
            font-size: 32rpx;
            color: #fff;
            text-align: center;
            line-height: 80rpx;
            background: #db187c;
            border-radius: 40rpx;
          }
        }
      }
    }
  }

  /deep/ u-parse {
    .wxParse {
      .img {
        display: block;
      }
    }
  }
</style>